package com.kcsj.service;
//李延杰
import com.kcsj.dao.ProductDao;
import com.kcsj.domain.Product;
import com.kcsj.util.Condition;
import com.kcsj.util.JdbcHelper;
import com.kcsj.util.Pagination;

import java.sql.Connection;
import java.sql.SQLException;
import java.util.Collection;
import java.util.List;

public class ProductService {
    public static final ProductService productService = new ProductService();
    public static final ProductDao productDao = ProductDao.getInstance();

    public static ProductService getInstance(){
        return productService;
    }

    public Collection<Product> findAll( List<Condition> conditionList)throws SQLException {
        Connection connection = JdbcHelper.getConn();
        Collection<Product> deliveryPeoples = productDao.findAll(conditionList,connection);
        JdbcHelper.close(connection);
        return deliveryPeoples;
    }

    public Product find(String productNo)throws SQLException{
        Connection connection = JdbcHelper.getConn();
        Product product = productDao.find(productNo,connection);
        JdbcHelper.close(connection);
        return product;
    }

    public boolean update(Product product) throws SQLException {
        Connection connection = JdbcHelper.getConn();
        connection.setAutoCommit(false);
        boolean judge = false;
        try {
            judge = productDao.update(product,connection);
            connection.commit();
        }catch (SQLException e){
            e.printStackTrace();
            connection.rollback();
        }finally {
            connection.setAutoCommit(true);
            JdbcHelper.close(connection);
        }
        return judge;
    }

    public int add(Product product) throws SQLException {
        Connection connection = JdbcHelper.getConn();
        connection.setAutoCommit(false);
        int num = 0;
        try{
            num = productDao.add(product,connection);
            connection.commit();
        }catch (SQLException e){
            e.printStackTrace();
            connection.rollback();
        }finally {
            connection.setAutoCommit(true);
            JdbcHelper.close(connection);
        }

        return num;
    }

    public boolean delete(String productNo) throws SQLException {
        Connection connection = JdbcHelper.getConn();
        connection.setAutoCommit(false);
        boolean judge = false;
        try {
            judge = productDao.delete(productNo,connection);
            connection.commit();
        }catch (SQLException e){
            e.printStackTrace();
            connection.rollback();
        }finally {
            connection.setAutoCommit(true);
            JdbcHelper.close(connection);
        }
        return judge;
    }

}
